package linter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
// import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import linter.POJO.DO.*;
import linter.POJO.DTO.UserDTO;
import linter.mapper.*;
import linter.service.UserService;
import linter.utils.JwtUtils;
import linter.utils.MD5Utils;
import linter.utils.PropertyUtils;
import linter.utils.RedisUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static linter.custom.Constant.*;

/**
* @author 北煜
* @description 针对表【user(用户基础信息表)】的数据库操作Service实现
* @createDate 2023-07-05 20:10:15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    UserMapper userMapper;

    @Resource
    UserCardMapper userCardMapper;

    @Resource
    UserRelationMapper userRelationMapper;

    @Resource
    UserSetMapper userSetMapper;

    @Resource
    UserStatusMapper userStatusMapper;

    @Resource
    CollectMapper collectMapper;

    /**
     * 根据用户名在数据库中查找用户
     */
    @Override
    public UserDTO getUserByUsername(String username) {
        return PropertyUtils.doToDto(userMapper.getUserByUsername(username), UserDTO.class);
    }

    /**
     * 定时查看用户组
     */
    @Scheduled(cron = "10 25 13 * * ?")
    public void test() {
        List<UserDTO> listUser = listUser();
        System.out.println(listUser);
    }
    public List<UserDTO> listUser() {
        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        return PropertyUtils.listToList(userList, UserDTO.class);
    }

    /**
     * @param username 用户名
     * @param pwd      密码
     * @return 返回token值
     */
    @Override
    public String checkLogin(String username, String pwd) {
        String encryptedPwd = MD5Utils.getMd5UserPwd(username,pwd);
        User user = userMapper.getUserByUsername(username);
        if (user == null) {
            return "用户不存在！";
        }
        if ( !encryptedPwd.equals(user.getPassword()) ) {
            return "密码错误！";
        }
        if (user.getState() !=0 ){
            return "用户已经被封禁";
        }
        Date date = new Date();
        String time = date.toString();
        // 生成token
        String token = JwtUtils.creatToken(username,time);
        RedisUtils.put(username,time,REFRESH_TOKEN_ACTIVE);
//        Integer role = user.getRole();
//        Map<String, String> map = new HashMap<>();
//        map.put("token",token);
//        map.put("role",role.toString());
//        return map.toString();
        return token;
    }


    @Override
    public Long register(String username, String pwd) {
        User user = new User();
        Date date = new Date();
        String encryptedPwd = MD5Utils.getMd5UserPwd(username,pwd);
        user.setUsername(username);
        user.setPassword(encryptedPwd);
        user.setCreateTime(date);
        user.setUpdateTime(date);
        Long flag = userMapper.insertThenById(user);
        user.setUsername(null);
        user.setPassword(null);
        flag += userStatusMapper.insert(PropertyUtils.doToDto(user, UserStatus.class));
        flag += userRelationMapper.insert(PropertyUtils.doToDto(user, UserRelation.class));
        flag += userSetMapper.insert(PropertyUtils.doToDto(user, UserSet.class));
        UserCard userCard = PropertyUtils.doToDto(user, UserCard.class);
        userCard.setSex(DEFAULT_USER_SEX);
        userCard.setSignature(DEFAULT_USER_SIGNATURE);
        userCard.setBirthday(date);
        userCard.setNickname("用户名称" + user.getId());
        userCard.setImgUrlIcon(DEFAULT_IMG_URL_ICON);
        flag += userCardMapper.insert(userCard);
        if (flag == 5L) {
            return flag;
        }
        if (removeById(user.getId())) {
            return 0L;
        }else {
            return -1L;
        }
    }

    /**
     * 重写removeById，将其删除所需表中的所需字段
     * @param id 用户ID
     * @return 返回删除成功没
     */
    public boolean removeAllById(Long id) {
        if (userMapper.deleteById(id) == 1){
            userCardMapper.deleteById(id);
            userRelationMapper.deleteById(id);
            userSetMapper.deleteById(id);
            userStatusMapper.deleteById(id);
            collectMapper.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public Long getIdByUsername(String username) {
        return userMapper.getIdByUsername(username);
    }

    @Override
    public  String loginPh(String phoneNumber){

        User user = userMapper.loginPh(phoneNumber);
        Date date = new Date();
        String time = date.toString();
        // TODO: 后续修改加入用户角色
        String token = JwtUtils.creatToken(user.getUsername(),time);
        RedisUtils.put(user.getUsername(),time,REFRESH_TOKEN_ACTIVE);
        return token;
    }
    @Override
    public  Boolean selectPh(String phoneNumber){
        return userMapper.selectPh(phoneNumber);
  }

  @Override
    public List<User> selectall(int pageNum, int pageSize,String username){
      PageHelper.startPage(pageNum, pageSize);
      QueryWrapper<User> queryWrapper = new QueryWrapper<>();
      if (username != null){
          queryWrapper.like("username", username);
      }
      queryWrapper.orderByDesc("update_time");
      List<User> list = userMapper.selectList(queryWrapper);
      return list;
  }

    @Override
    public Integer getUserRole(String username) {
        return userMapper.getUserRole(username);
    }

    @Override
    public String ban(int id,int state) {
        if (state == 0){
            if (userMapper.ban(id)){
                return "账号已封禁";
            }
            return "遇到意料之外的情况请联系管理员";
        }
        if (state == 1){
            if (userMapper.unseal(id)){
                return "账号已解封";
            }
            return "遇到意料之外的情况请联系管理员";
        }
        return "用户的状态似乎有些问题,请联系管理员";
    }


}




